package com.project.restaurant.user.service.impl;

import com.project.restaurant.common.api.ResponseResult;
import com.project.restaurant.common.api.ServiceStateCode;
import com.project.restaurant.common.exception.ServiceException;
import com.project.restaurant.common.key.SessionAttribute;
import com.project.restaurant.common.util.SpringUtil;
import com.project.restaurant.mapper.UserMapper;
import com.project.restaurant.pojo.User;
import com.project.restaurant.user.dto.UpdateFileInfo;
import com.project.restaurant.user.dto.UpdateUserInfoParam;
import com.project.restaurant.user.feign.FastDFSService;
import com.project.restaurant.user.service.UserInfoService;
import com.project.restaurant.user.vo.UserPublicInfoVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: restaurant
 * @BelongsPackage: com.project.restaurant.user.service
 * @Author: hanhan
 * @CreateTime: 2022-10-20  08:56
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    FastDFSService fastDFSService;

    @Resource
    UserMapper userMapper;

    @Override
    public String updateAvatar(HttpSession session,MultipartFile avatar) throws Exception {
        byte[] bytes = avatar.getBytes();
        User user = (User) session.getAttribute(SessionAttribute.NOW_LOGIN_USER);
        try{
            ResponseResult<String> result = fastDFSService.fileUpload(bytes);
            if (result.isSuccess()){
                user.setUserAvatar(result.getData());
                int i = userMapper.updateById(user);
                if (i==1){
                    session.setAttribute(SessionAttribute.NOW_LOGIN_USER,user);
                    return result.getData();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        throw  new ServiceException(ServiceStateCode.FAILURE);
    }

    @Override
    public UserPublicInfoVo updateInfo(UpdateUserInfoParam updateInfo) {
        HttpSession session = SpringUtil.getHttpSession();
        User user = (User) session.getAttribute(SessionAttribute.NOW_LOGIN_USER);
        if(updateInfo.updateUserInfo(user)){
            int update = userMapper.updateById(user);
            if(update != 1){
                throw new ServiceException(ServiceStateCode.FAILURE);
            }
            session.setAttribute(SessionAttribute.NOW_LOGIN_USER,user);
        }
        return UserPublicInfoVo.getUserSafeInfoVo(user);
    }
}
